<?php

namespace App\Http\Controllers;

use App\Jobs\Address2CoordinateTransJob;
use App\Models\MdClient;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;


/**
 * Class MdClientController
 * @package App\Http\Controllers
 * create_at: 2025-01-11 10:05:52
 * update_at: 2025-01-11 10:05:52
 */
class MdClientController extends Controller
{
    const KEY = "A6ABZ-5QF65-2PBI6-INQHP-EB7PF-KKFUG";
    const API_URL = "https://apis.map.qq.com/ws/geocoder/v1/";
    const ON_QUEUE = "address2coordinatetrans";

    /**
     * run
     * create_at: 2025-01-11 08:43:14
     * update_at: 2025-01-11 08:43:14
     */
    public function run()
    {
        // 获取所有的客户信息
        $allClients = MdClient::where(["mark" => 1])->limit(1000)->get();
        foreach ($allClients as $client) {
//            $this->handleJob($client);
            Address2CoordinateTransJob::dispatch($client)->onQueue(self::ON_QUEUE);
        }
    }

    /**
     * 单条记录处理
     * @param $client
     * @throws \Illuminate\Http\Client\ConnectionException
     * create_at: 2025-01-11 09:55:57
     * update_at: 2025-01-11 09:55:57
     */
    public function handleJob($client)
    {
        // 如果地址为空，则跳过
        if (empty($client->address)) {
            $this->markExcp($client->client_id);
            return;
        }

        // 请求
        $response = Http::retry(0)->withQueryParameters([
            'key' => self::KEY,
            'address' => urlencode($client->address)
        ])->get(self::API_URL);

        if ($response->ok()) {
            $res = $response->json();
            if (isset($res["status"]) && 0 == $res["status"] && "Success" == $res["message"]) {
                $lng = $res["result"]["location"]["lng"];
                $lat = $res["result"]["location"]["lat"];
                $proName = $res["result"]["address_components"]["province"];
                $cityName = $res["result"]["address_components"]["city"];
                $districtName = $res["result"]["address_components"]["district"];

                DB::table("md_client")->where(["client_id" => $client->client_id])->update([
                    "lng" => $lng,
                    "lat" => $lat,
                    "pro_name" => $proName,
                    "city_name" => $cityName,
                    "district_name" => $districtName,
                    "mark" => 2
                ]);
            } else {
                $this->markExcp($client->client_id);
            }
        }
    }

    /**
     * markExcp
     * @param $client_id
     * create_at: 2025-01-11 10:40:51
     * update_at: 2025-01-11 10:40:51
     */
    protected function markExcp($client_id)
    {
        DB::table("md_client")->where(["client_id" => $client_id])->update([
            "mark" => 3
        ]);
    }
}
